from dataclasses import dataclass
from enum import Enum
from typing import Optional
import time
import random
import string
import os

DATA_FILES = {
    1: 'data_files/data_1kb.txt',
    10: 'data_files/data_10kb.txt',
    100: 'data_files/data_100kb.txt',
    1000: 'data_files/data_1000kb.txt'
}


def read_data_file(size_kb: float) -> str:
    """
    从文件读取数据，根据输入的大小组合文件。

    Args:
        size_kb: 需要读取的总大小，单位为 KB。

    Returns:
        读取到的字符串数据。
    """

    data = ""
    size_kb=int(size_kb)
    if size_kb <= 0:
        return ""
    remaining_size = size_kb

    # 从最大的文件开始，尽可能多地读取
    for size in sorted(DATA_FILES.keys(), reverse=True):
        num_copies = remaining_size // size
        if num_copies > 0:
            filename = DATA_FILES[size]
            # print(f"读取数据文件: {filename} {num_copies} 次")
            try:
                with open(filename, 'r') as f:
                    file_content = f.read()
                    data += file_content * num_copies
            except FileNotFoundError:
                print(f"错误：文件未找到：{filename}")
                return None  # 或者抛出异常
            remaining_size -= size * num_copies
    return data


@dataclass
class Task:
    id: str  # 任务唯一标识符
    task_type: str  # 任务类型
    max_delay: float  # 最大容忍延迟(秒)
    compute_load: float  # 计算负载(GHz)
    data_size: float  # 数据大小(MB)
    submit_time: float  # 到达时间
    input_data: str  # 输入数据
    start_time: Optional[float] = None  # 开始执行时间
    completion_time: Optional[float] = None  # 完成时间

    @classmethod
    def create_random_task(cls, task_id: str, task_type: str,
                           max_delay: float, compute_load: float,
                           data_size: float) -> 'Task':
        """创建带有数据的任务"""
        # print(f"创建任务 {task_id}: 类型={task_type}, "
        #       f"计算负载={compute_load}, 数据大小={data_size}MB")
        return cls(
            id=task_id,
            task_type=task_type,
            max_delay=max_delay,
            compute_load=compute_load,
            data_size=data_size,
            submit_time=time.time(),
            input_data=read_data_file(data_size)
        )

    def is_failed(self) -> bool:
        """检查任务是否已超时"""
        if self.completion_time is None:
            current_time = time.time()
            return (current_time - self.submit_time) > self.max_delay
        return (self.completion_time - self.submit_time) > self.max_delay
